package accepttests;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import database.PasswdDatabaseManager;
import user.User;
import user.profile.*;

/**
 * Fa�ade class used for Profile's acceptance tests.
 * 
 * @author Cassio Espindola - cassioafonso@gmail.com
 * 
 */
public class ProfileFacade {
	private List<Profile> profileList;

	public ProfileFacade() {
		profileList = new ArrayList<Profile>();
	}

	public void createProfile(String login, String senha, String nome_exibicao,
			String email, String sexo, String dataNasc, String endereco,
			String interesses, String quem_sou_eu, String filmes,
			String musicas, String livros) throws Exception {
		Profile profile = new Profile(login, senha, nome_exibicao, email, sexo,
				dataNasc, endereco, interesses, quem_sou_eu, filmes, musicas,
				livros);
		verifyProfile(profile);
		profileList.add(profile);
		User user = new User(login, senha, profile);
		user.save();
	}

	private void verifyProfile(Profile profile) throws Exception {
		Iterator<Profile> itProfiles = profileList.iterator();
		while (itProfiles.hasNext()) {
			Profile tempProfile = itProfiles.next();

			if (profile.getPersonalProperty(Flags.EMAIL).equals(
					tempProfile.getPersonalProperty(Flags.EMAIL))) {
				throw new Exception("Email existente");
			}

			if (profile.getPersonalProperty(Flags.LOGIN).equals(
					tempProfile.getPersonalProperty(Flags.LOGIN))) {
				throw new Exception("Login existente");
			}
		}
	}

	public void cleanPersistence() {
		new File("Database/mariasilva.xml").delete();
		new File("Database/sicrano.xml").delete();
		new File("Database/passwd.xml").delete();
	}

	public Object getProfileInformation(String login, String atributo)
			throws Exception {
		Iterator<Profile> itProfiles = profileList.iterator();
		while (itProfiles.hasNext()) {
			Profile tempProfile = itProfiles.next();
			if (tempProfile.getPersonalProperty(Flags.LOGIN).equals(login)) {
				return tempProfile.getPersonalProperty(atributo);
			}
		}

		return null;
	}

	public void saveData() throws Exception {
		Iterator<Profile> itProfiles = profileList.iterator();
		PasswdDatabaseManager pdm = PasswdDatabaseManager.getInstance();
		while (itProfiles.hasNext()) {
			Profile tempProfile = itProfiles.next();
			tempProfile.save();
			pdm.setPasswd(
					tempProfile.getPersonalProperty(Flags.LOGIN.getFlag()),
					tempProfile.getPersonalProperty(Flags.EMAIL.getFlag()));
		}
		pdm.save();
	}
}
